<?php
class C_categories extends CI_Controller{
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('myclass');
        $this->myclass->not_admin();
    }
    /**
     * add categorie
     */
    public function add_categories(){
        //kiem tra ton tai post
        $data=array();
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $errors = array();//mang chua loi
            if(empty($_POST['category'])){
                $errors[]='category';
            }  else {
                $cat_name = $_POST['category'];
            }
            if(empty($errors)){
                $this->load->model('M_categories');
                $data['cat']= $this->M_categories->add_categories($cat_name);
                $data['mg1'] = " add thanh cong";
                if($data['cat']!=1){
                    $data['mg1'] = " add xit";
                }
             }else{
                $data['mg2'] = "dien category";
                }
            }
        $this->load->view('v_add_categories',$data);
    }
    
    public function view_categories(){

        $this->load->model('M_categories');
        $data['categories'] = $this->M_categories->view_categories();
        $this->load->view('v_view_categories',$data);

    }
    public function edit(){

        //in ra du lieu trong form de edit
        $this->load->model('M_categories');
        $dt= $data['category'] = $this->M_categories->view_category($_GET['cat']);
        
        // sau khi submit
        
        if(isset($_POST['category'])&& $_POST['category']==$dt[0]['cat_name']){
            $data['mg1'] = " ban da ko edit ji ca";
        }
        if(isset($_POST['category'])&& $_POST['category']!=$dt[0]['cat_name']){
            //update vao csdl
            $cat_name = $_POST['category'];
            $this->load->model('M_categories');
            $data['flag'] = $this->M_categories->update_category($cat_name,$_GET['cat']);
            if($data['flag']==1){
                $data['mg1'] = " edit thanh cong";
            }else{
                $data['mg1'] = " edit xit";
            }
        }
        //load lai du lieu hien thi trong form
        $this->load->model('M_categories');
        $dt= $data['category'] = $this->M_categories->view_category($_GET['cat']);
        // goi ra view
        $this->load->view('v_edit_categories',$data);
    }
    public function delete(){

        $data=array();
        if(isset($_GET['cat'])){
            //echo $_GET['cat'];
            $this->load->model('M_categories');
            $data['flag'] = $this->M_categories->delete($_GET['cat']);
            //doan nay quan trong can phai nho va tim hieu
            $this->load->helper('url');
            redirect('c_categories/view_categories');
        }
    }
    
}
?>
